// message.js
// Implement message reading and notification. Note that 'message' means 
// those sent between users while 'messaging' means those sent between 
// extension components.

var ShowMessageNotification = (function(){});
function UpdateMessageCount()
{
	XHR.SendRequest("/", (function(xhr)
	{
		var windid = xhr.responseText.match(/var\s*windid\s*=\s*'(.*?)';/);
		var result = xhr.responseText.match(
			/<span id="msgnum_show">(\d*)<\/span>/);
		if(result)
		{
			chrome.browserAction.setBadgeText({text: result[1]});
			Options.Notifications.NewMessageNotification && 
				ShowMessageNotification();
		}
		else if(windid && windid[1])
			chrome.browserAction.setBadgeText({text: ""});
		else
			chrome.browserAction.setBadgeText({text: "?"});
	}), (function()
	{
		chrome.browserAction.setBadgeText({text: "!"});
	}) );
}

var MessageEntryRegEx_String = '<td><a href="u\\.php\\?action=show&uid=(\\d+)">(.*?)</a></td>\\s*<td><a href="message\\.php\\?action=(readn?)&mid=(\\d+)">(.*?)</a></td>\\s*<td>(.*?)</td>';
var MessageEntryRegEx = new RegExp();
var MessageEntryRegExG = new RegExp();
MessageEntryRegEx.compile(MessageEntryRegEx_String, "i");
MessageEntryRegExG.compile(MessageEntryRegEx_String, "ig");

function ReadNewMessages(callback)
{
	XHR.SendRequest("/message.php?type=newmsg", (function(xhr)
	{
		var results = [];
		var messages = xhr.responseText.match(
			/<tr><td colspan="5"><b>未读(个人|系统)短消息<\/b><\/td><\/tr>[\s\S]*?<\/table>/);
		if(!messages)
		{
			chrome.browserAction.setBadgeText({text: ""});
			callback(results);
			return;
		}
		var entries = messages[0].match(MessageEntryRegExG);
		if(!entries)
		{
			chrome.browserAction.setBadgeText({text: ""});
			callback(results);
			return;
		}
		for(var i = 0; i < entries.length; ++i)
		{
			var matches = entries[i].match(MessageEntryRegEx);
			if(matches)
				results[results.length] = 
				{
					fromUid: matches[1], 
					fromUser: matches[2], 
					actionId: matches[3], 
					id: matches[4], 
					title: matches[5], 
					time: matches[6], 
				};
		}
		chrome.browserAction.setBadgeText({text: results.length.toString()});
		callback(results);
	}), (function(xhr)
	{
		callback();
	}));
}

function GetMessageURL_PathName(message)
{
	return "/message.php?action=" + message.actionId + "&mid=" + 
		message.id;	
}

function ShowMessage(message)
{
	var pathname = GetMessageURL_PathName(message);
	var fullurl = XHR.GetURL(pathname);
	if(message.fromUser == "SYSTEM" && message.fromUid == "0" && 
		/^Hi，.*?@你了$/.test(message.title))
	{
		XHR.SendRequest(pathname, (function(xhr)
		{
			var target = xhr.responseText.match(
				/<a href="(.*?)">点这里看看吧<\/a>/);
			if(target && target[1])
				CreateTab(target[1]);
			else
				CreateTab(pathname);
		}), (function()
		{
			CreateTab(pathname);
		}));
	}
	else
		CreateTab(pathname);
}

var lastMessageId = "";
var lastMessageTime = new Date(0);
ShowMessageNotification = (function(){ReadNewMessages(function(results)
{
	if(results && results[0] && results[0].id != lastMessageId && 
		(new Date(results[0].time)) >= lastMessageTime)
	{
		lastMessageId = results[0].id;
		lastMessageTime = new Date(results[0].time);
		var notification = webkitNotifications.createNotification(
			"images/icons/qshpan_48.png", 
			"新消息", 
			results[0].fromUser + ": " + results[0].title);
		notification.onclick = (function()
		{
			ShowMessage(results[0]);
			notification.cancel();
		});
		notification.show();
	}
})});

(chrome.extension.onMessage || chrome.extension.onRequest).addListener(
function(message, sender, sendResponse)
{
	if(message.name && message.name == "updateMessageCount" && 
		message.value != undefined && /^(\d*|\?)$/.test(message.value))
	{
		chrome.browserAction.setBadgeText({text: message.value});
		if(message.value != "?" && Options.Domain.Preference == "custom")
		{
			var domain = ((sender.tab || {}).url || "").match(
				/^http:\/\/(.*?)\//);
			if(domain && domain[1])
				Options.Domain.Current = domain[1];
		}
	}
});
var interval_UpdateMessageCount;
Options.Notifications.onChanged = (function()
{
if(Options.Notifications.UpdateUnreadMessageInterval)
{
	interval_UpdateMessageCount = window.setInterval(UpdateMessageCount, 
		1000 * Options.Notifications.UpdateUnreadMessageInterval);
	UpdateMessageCount();
}
else
{
	window.clearInterval(interval_UpdateMessageCount);
	chrome.browserAction.setBadgeText({text: ""});
}
});
if(Options.Notifications.UpdateUnreadMessageInterval)
{
	interval_UpdateMessageCount = window.setInterval(UpdateMessageCount, 
		1000 * Options.Notifications.UpdateUnreadMessageInterval);
	DomainReadyCallback = UpdateMessageCount(); //defined in domain.js
}

